<?php

namespace Encore\WangEditorPro;

use Encore\Admin\Form\Field\File;
use Encore\Admin\Admin;

class EditorPro extends File
{
    protected $view = 'laravel-admin-wangEditorPro::editor';

    protected static $css = [
        'vendor/laravel-admin-ext/wang-editor-pro/wangEditor-3.1.1/release/wangEditor.css',
    ];

    protected static $js = [
        'vendor/laravel-admin-ext/wang-editor-pro/wangEditor-3.1.1/release/wangEditor.js',
    ];

    /**
     * 获取html字符串内所有img标签的图片链接
     * @return [array] [imgPathArray]
     */
    private function getDocumentImg($str)
    {
        $pattern = "/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png|\.bmp]))[\'|\"].*?[\/]?>/is";
        preg_match_all($pattern , $str , $matches);
        return $matches[1];
    }

    /**
     * 文档内图片更新
     * @param $newDocument
     * @param $oldDocument
     */
    private function documentImgUpdate($oldDocument,$newDocument)
    {
        $oldImgArray = $this->getDocumentImg($oldDocument);
        $newImgArray = $this->getDocumentImg($newDocument);

        //比较新旧图片数组 获取差集(被删除的图片)
        $deleteImgArray = array_diff($oldImgArray,$newImgArray);
        if (!empty($deleteImgArray)) {
            foreach ($deleteImgArray as $v) {
                //删除被遗弃的文件
                @unlink(public_path($v));
            }
        }
    }

    /**
     * 文档内图片删除
     * @param $document
     */
    private function documentImgDelete($document)
    {
        $deleteImgArray = $this->getDocumentImg($document);
        if (!empty($deleteImgArray)) {
            foreach ($deleteImgArray as $v) {
                //删除被遗弃的文件
                @unlink(public_path($v));
            }
        }
    }

    /**
     * 文档保存前预处理。解决文件冗余情况
     */
    public function prepare($document)
    {
        $this->documentImgUpdate($this->original,$document);
        return $document;
    }

    public function render()
    {
        $name = $this->formatName($this->column);

        $config = (array) WangEditorPro::config('config');

        $config = json_encode(array_merge([
            'zIndex'              => 0,
            'uploadImgShowBase64' => false,
            'pasteFilterStyle'    => false,
        ], $config, $this->options));

        $token = csrf_token();

        $this->script = <<<EOT

var E = window.wangEditor
var editor = new E('#{$this->id}');

editor.customConfig.uploadImgParams = {_token: '$token'}

Object.assign(editor.customConfig, {$config})

//强制文件上传地址为预设的地址
editor.customConfig.uploadImgServer = '/wangEditorProUpload';

editor.customConfig.onchange = function (html) {
    $('input[name=$name]').val(html);
}
editor.create()

EOT;

        if (!$this->display) {
            return '';
        }

        Admin::script($this->script);

        return view($this->getView(), $this->variables());
    }

    /**
     * 数据销毁回调 用于删除富文本编辑器内的图片
     */
    public function destroy()
    {
        $this->documentImgDelete($this->original);
    }
}
